//
//  JXMineController.m
//  JiaoX
//
//  Created by jiaoxiu－004 on 14-10-11.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//
#import "JXMineController.h"
#import "WXApi.h"
#import "SelfArrowItemInfo.h"
#import "SelfSwitchItemInfo.h"
#import "SelfItemCell.h"
#import "SelfHeaderView.h"
#import "JXOrderViewController.h"
#import "JXLoginController.h"
#import "JXNavigationController.h"
#import "UserDefaultsHelper.h"
#import "JXModifyInfoController.h"
#import "JXLoginRegistCheckController.h"
#import "JXAddressListController.h"
#import "JXFeedbackController.h"
#import "SelfDataTool.h"
#import "MyPageInfo.h"
#import "JXMyMarkController.h"
#import "JXRecommendController.h"
#import "JXPrivacyPwdController.h"
#import "JXAboutUsController.h"
#import "JXAppInfo.h"
#import "JXChatManager.h"
#import "JXVolumeCtrl.h"
#import "ShareOrderPopView.h"
#import "CustomShowView.h"
#import "JXShakeCtl.h"


@interface JXMineController ()<UITableViewDataSource,UITableViewDelegate,SelfHeaderViewDelegate,UIAlertViewDelegate,PrivacyPwdDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_allGroups; // 所有的组模型
    
}
@property(nonatomic,strong)SelfHeaderView *header;

@end

@implementation JXMineController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我";
    self.view.backgroundColor = [UIColor whiteColor];
    _allGroups = [NSMutableArray array];
    
    //添加一个分组类型的tableview;
    CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    UITableView *tableVeiw = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
    tableVeiw.backgroundColor = JXGlobalColorBg;
    [tableVeiw setSeparatorColor:SEPARATORCOLOR];
    tableVeiw.sectionFooterHeight = 15;
    tableVeiw.sectionHeaderHeight = 15;
    //headerView
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, JXScreenW, 0.01)];
    view.backgroundColor = [UIColor clearColor];
    SelfHeaderView *header = [[SelfHeaderView alloc]init];
    self.header = header;
    header.delegate = self;
    tableVeiw.tableHeaderView = header;
    tableVeiw.tableFooterView = view;
    [self.view addSubview:tableVeiw];

    _tableView = tableVeiw;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    
    // 1.第0组：3个
//    [self add0SectionItems];
    // 2.第1组：5个
    [self add1SectionItems];
    // 3.第2组：4个
    [self add2SectionItems];
    // 4.第3组：1个
    [self add3SectionItems];
    
    [self add4SectionItems];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:@"applicationDidBecomeActive" object:nil];
}


-(void)add0SectionItems{
    SelfArrowItemInfo *orderItem = [SelfArrowItemInfo itemWithIcon:@"self_item_order" title:@"订单" subTitle:@"" hasNew:NO];
    [orderItem setShowVCClass:[JXOrderViewController class]];
    
    SelfArrowItemInfo *markItem = [SelfArrowItemInfo itemWithIcon:@"self_item_mark" title:@"收藏" subTitle:nil hasNew:NO];
    [markItem setShowVCClass:[JXMyMarkController class]];

    SelfArrowItemInfo *addressItem = [SelfArrowItemInfo itemWithIcon:@"self_item_address" title:@"收货地址" subTitle:@"" hasNew:NO];
    [addressItem setShowVCClass:[JXAddressListController class]];
    
    NSArray *Items = @[orderItem, markItem];

    [_allGroups addObject:Items];
}


-(void)add1SectionItems{
    SelfSwitchItemInfo *pwdItem = [SelfSwitchItemInfo itemWithIcon:@"self_item_pwd" title:@"启动密码" subTitle:@"保护隐私" hasNew:NO];
    [pwdItem setKey:KEY_PWD_STATUS];
    [pwdItem setOperation:^{
        SelfSwitchItemInfo *info = _allGroups[0][0];
        JXPrivacyPwdController *ctrl = [[JXPrivacyPwdController alloc]initWithFromType:info.on?FROM_TYPE_SELFFRG_SET:FROM_TYPE_SELFFRG_CLOSE];
        JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:ctrl];
        ctrl.delegate = self;
        [self presentViewController:nav animated:YES completion:nil];
    }];
    
    SelfSwitchItemInfo *showPicItem = [SelfSwitchItemInfo itemWithIcon:@"self_item_showpic" title:@"显示图片" subTitle:@"2G/3G/4G" hasNew:NO];
    [showPicItem setKey:KEY_SHOW_PIC];
    [showPicItem setOperation:^{
        AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        myDelegate.isCanLoadPic = [Utils isCanLoadPic];
    }];
    
    SelfSwitchItemInfo *pushItem = [SelfSwitchItemInfo itemWithIcon:@"self_item_push" title:@"接受通知" subTitle:nil hasNew:NO];
    [pushItem setOperation:^{
        SelfSwitchItemInfo *info = _allGroups[0][2];
        if([Utils isAllowPush]){
            if (info.on) {
                [Utils openPush];
            }else{
                [Utils closePush];
            }
            [UserDefaultsHelper setBool:info.on forKey:KEY_PUSH_STATUS];
        }else{
            //用户本来是不允许接收通知消息的，现在要在这打开，需要弹出提示，叫用户去设置，通知里面去打开。
            [DialogUtils showTipsWithView:self.navigationController.view String:@"你还未开启消息推送允许，请先在系统设置中打开消息通知允许"];
            info.on = NO;
            [_tableView reloadData];
        }
    }];
    pushItem.on=[UserDefaultsHelper boolForKey:KEY_PUSH_STATUS];
    
//    SelfArrowItemInfo *reviewsItem = [SelfArrowItemInfo itemWithIcon:@"self_item_reviews" title:@"测评提醒" subTitle:nil hasNew:YES];

    
    SelfArrowItemInfo *addressItem = [SelfArrowItemInfo itemWithIcon:@"self_item_address" title:@"收货地址" subTitle:@"" hasNew:NO];
    [addressItem setShowVCClass:[JXAddressListController class]];
    
    NSArray *Items = @[pwdItem, showPicItem, pushItem,addressItem];
    [_allGroups addObject:Items];
}

-(void)add2SectionItems{
    SelfArrowItemInfo *feedBackItem = [SelfArrowItemInfo itemWithIcon:@"self_item_feedback" title:@"意见反馈" subTitle:nil hasNew:NO];
    [feedBackItem setShowVCClass:[JXFeedbackController class]];
    
    SelfArrowItemInfo *aboutItem = [SelfArrowItemInfo itemWithIcon:@"self_item_about" title:@"关于娇羞" subTitle:nil hasNew:NO];
    [aboutItem setShowVCClass:[JXAboutUsController class]];
    
    SelfArrowItemInfo *praiseItem = [SelfArrowItemInfo itemWithIcon:@"self_item_praise" title:@"给个好评" subTitle:nil hasNew:NO];
    [praiseItem setOperation:^{
        NSString *url = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=962235381";//942925112
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }];
    
    SelfArrowItemInfo *recomdItem = [SelfArrowItemInfo itemWithIcon:@"self_item_recomd" title:@"精品推荐" subTitle:nil hasNew:NO];
    [recomdItem setShowVCClass:[JXRecommendController class]];
    [_allGroups addObject:@[feedBackItem, aboutItem,praiseItem]];
}

-(void)add3SectionItems{
    SelfItemInfo *clearCache = [SelfItemInfo itemWithIcon:@"self_item_clear" title:@"点击清除缓存" subTitle:nil hasNew:NO];
    clearCache.operation = ^(void){
        [[SDImageCache sharedImageCache] clearDisk];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"清除完毕"];
    };
    [_allGroups addObject:@[clearCache]];
}

-(void)add4SectionItems{
    SelfItemInfo *loginOutItem = [SelfItemInfo itemWithIcon:nil title:@"退出登录" subTitle:nil hasNew:NO];
    loginOutItem.operation = ^(void){
        [self logout];
    };
    [_allGroups addObject:@[loginOutItem]];
}

#pragma mark - Table view 数据源
/**
 *  返回一共有多少组
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(!TOKEN){
         return _allGroups.count-1;
    }
    return _allGroups.count;
}

/**
 *  返回每一组有多少个
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *group = _allGroups[section];
    return group.count;
}

/**
 *  返回对应位置的cell
 *
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建一个cell
    SelfItemCell *cell = [SelfItemCell itemCellWithTableView:tableView];
    
    SelfItemInfo *info =  _allGroups[indexPath.section][indexPath.row];
    
    cell.item = info;
    cell.indexPath = indexPath;
    return cell;
}

#pragma mark - Table view 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //去除选中效果
    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    SelfItemInfo *info =  _allGroups[indexPath.section][indexPath.row];
    if([info isKindOfClass:[SelfArrowItemInfo class]]){
        SelfArrowItemInfo *arrowItem =(SelfArrowItemInfo *)info;
        if(arrowItem.showVCClass){
            [self.navigationController pushViewController:[[arrowItem.showVCClass alloc]init] animated:true];
        }else if(arrowItem.operation!=nil){
            arrowItem.operation();
        }
    }else if(![info isKindOfClass:[SelfSwitchItemInfo class]] && info.operation!=nil){//退出登录
        info.operation();
    }
}

/**
 *  退出登录
 */
-(void)logout{
    NSString *token = [UserDefaultsHelper stringForKey:KEY_APPTOKEN];
    if([Utils isBlankString:token])return;//判断token 不存在就是未登录
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确定退出吗？" message:@"" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    [alert show]; //显示退出对话框
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {     // and they clicked OK.
        [_header setOrderNum:0];
        [Utils clearUserInfo];
        [self resetHeaderBtn];
        [_allGroups[0] makeObjectsPerformSelector:@selector(setSubtitle:) withObject:@""];
        [self.header adjustLocation:NO];
    }
}

/**
 *点击登录
 */
-(void)loginBtnClick{
    NSString *title = self.header.nameLabel.text;
    if([title isEqualToString:@""]){//昵称为空，说明没有登录，跳转到登录页
        JXNavigationController *nav = [[JXNavigationController alloc]initWithRootViewController:[[JXLoginRegistCheckController alloc]init]];
        [self presentViewController:nav animated:true completion:^{}];
    }else{//昵称不为空，说明为登录状态，跳转到个人信息页
       [self.navigationController pushViewController:[[JXModifyInfoController alloc]init] animated:true];
    }
}

/**
 *  重置header
 */
- (void)resetHeaderBtn {
    //重置layer
    CALayer *layer=[self.header.loginBtn layer];
    [layer setCornerRadius:31];
    //是否设置边框以及是否可见
    [layer setMasksToBounds:NO];
    //设置边框线的宽
    [layer setBorderWidth:2];
    //设置边框线的颜色
    [layer setBorderColor:[[UIColor clearColor] CGColor]];
    [self.header.loginBtn setBackgroundImage:[UIImage imageNamed:@"self_header_login_pre"] forState:UIControlStateNormal];
    [self.header.loginBtn setBackgroundImage:[UIImage imageNamed:@"self_header_login_nor"] forState:UIControlStateHighlighted];
    [self.header.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.header.nameLabel setText:@""];
    [_tableView reloadData];
}

-(void)viewWillAppear:(BOOL)animated{//每次展示都会回调的方法
    [super viewWillAppear:animated];
    if(TOKEN){//token不为空说明已经登录,显示用户昵称和头像
        //刷新一下列表，用于登录完成后显示退出登录的cell
        [[JXChatManager sharedInstance] getSignAndOpenSession];
        //显示头像
        NSString *headImg = [UserDefaultsHelper stringForKey:KEY_USER_IMG];
        [self.header.loginBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:headImg] forState:UIControlStateNormal];
        [self.header.loginBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:headImg] forState:UIControlStateHighlighted];
        
        [self.header.loginBtn setTitle:@"" forState:UIControlStateNormal];
        
        //设置layer
        CALayer *layer=[self.header.loginBtn layer];
        [layer setCornerRadius:self.header.loginBtn.width/2];
        //是否设置边框以及是否可见
        [layer setMasksToBounds:YES];
        //设置边框线的宽
        [layer setBorderWidth:2];
        //设置边框线的颜色
        [layer setBorderColor:[[UIColor whiteColor] CGColor]];
        
        //显示昵称
        NSString *nickname = [UserDefaultsHelper stringForKey:KEY_NICK_NAME];
        CGSize nickNameSize = [nickname sizeWithFont:self.header.nameLabel.font];
        self.header.nameLabel.frame = CGRectMake(JXScreenW/2-nickNameSize.width/2, self.header.nameLabel.y, nickNameSize.width, nickNameSize.height);
        [self.header.nameLabel setText:nickname];
        
        [self.header adjustLocation:YES];
        [self.header setVip:[UserDefaultsHelper integerForKey:KEY_USER_LEVEL]];
        //请求个人中心的数据
        [self requestData];
    }else{
        [_header setOrderNum:0];
        [_allGroups[0] makeObjectsPerformSelector:@selector(setSubtitle:) withObject:@""];
        [self resetHeaderBtn];
        [self.header adjustLocation:NO];
    }
    
    //密码开关状态
    NSString *pwd = [UserDefaultsHelper stringForKey:KEY_HAVE_PASSWORD];
    SelfSwitchItemInfo *info = _allGroups[0][0];
    if ([Utils isBlankString:pwd]) {
        info.on = NO;
    }else{
        info.on = YES;
    }
    
    //显示是否有新版
    JXAppInfo *app = [NSKeyedUnarchiver unarchiveObjectWithFile:JXAppInfoFilePath];
    if (app) {
        if([app.appVersion compare:[Utils getAppVersion]]==NSOrderedDescending){
            //有新版
            SelfItemInfo *info =  _allGroups[1][1];
            [info setHasNew:YES];
        }
    }
    
    [self becomeActive];
}

-(void)becomeActive{
    SelfSwitchItemInfo *pushinfo = _allGroups[0][2];
    if (![Utils isAllowPush]) {
        //用户关闭了接收通知
        pushinfo.on = NO;
    }else{
        pushinfo.on = [UserDefaultsHelper boolForKey:KEY_PUSH_STATUS];
    }
    [_tableView reloadData];
}

-(void)requestData{
    [SelfDataTool getUserOtherInfo:^(MyPageInfo *result) {
        if ([Utils isBlankString:result.data]) {
            
            //订单
            if(result.orderNum)
                [_header setOrderNum:result.orderNum];
            else
                [_header setOrderNum:0];
            //收藏
            if (![Utils isBlankString:result.address]) {
                SelfItemInfo *info =  _allGroups[0][3];
                [info setSubtitle:result.address];
            }else{
                SelfItemInfo *info =  _allGroups[0][3];
                [info setSubtitle:@""];
            }
            [self.header setVip:result.level];
            [UserDefaultsHelper setInteger:result.level forKey:KEY_USER_LEVEL];
            [_tableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)clickVolume{
    [self.navigationController pushViewController:[JXVolumeCtrl initWithPrice:nil prodPrice:-1 isChoice:NO type:MINE_TYPE] animated:true];
}

-(void)clickOrder{
    [self.navigationController pushViewController:[[JXOrderViewController alloc]init] animated:true];
}

-(void)clickMark{
    [self.navigationController pushViewController:[[JXMyMarkController alloc]init] animated:true];
}

-(void)endSetPwd{
    [DialogUtils showTipsWithView:self.navigationController.view String:@"操作成功"];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
